package com.kool.kmqtt.server.task;

import com.kool.kmqtt.server.ServerConfig;
import com.kool.kmqtt.server.session.SessionContext;
import com.kool.kmqtt.server.session.SessionHolder;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

@Slf4j
public class KeepliveTimeoutTask implements Runnable{
    @Override
    public void run() {
        try {
            //轮询会话
            while (true) {
                try {
                    List<SessionContext> sessionContexts = SessionHolder.getInstance().getAllCopy();
                    if (sessionContexts != null) {
                        for (SessionContext sessionContext : sessionContexts) {
                            //心跳超时，断开连接
                            if (sessionContext.getLastKeepAliveTime() != null
                                    && sessionContext.getKeepAlive() != null
                                    && sessionContext.getLastKeepAliveTime().getTime() + sessionContext.getKeepAlive() * 1500 < System.currentTimeMillis()) {
                                log.debug("客户端[{}]连接超时，上次心跳时间：{}，当前时间：{}", sessionContext.getClientId(), sessionContext.getLastKeepAliveTime(), new Date());
                                SessionHolder.close(sessionContext);
                            }
                        }
                    }
                    Thread.sleep(ServerConfig.getInstance().getKeepAliveInterval());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
        }
    }
}
